
import {doCache, doSave} from "@/utils/offline/sqlite/index.js"

import * as XUNJIAN from '@/api/engineeringMaintenance/engineeringMaintenance.js'
// #ifdef APP-PLUS
import { DB } from "@/utils/offline/sqlite/dbinit.js";
// #endif
import { networkOnline } from "@/utils/offline/config"
const currPage = 1
const pageSize = 9999
export async function before({projectId}) {	
	if(!(await networkOnline())){
		uni.showToast({
			title:"当前网络不稳定",
			icon:'none',
			mask:true
		})
		throw new Error('当前网络不稳定！！！')
	}  
	//当表新增列时，需要执行一遍删表操作，
	// 判断表中某个是否存在，不存在则添加该字段
	
	//区间站点表
	let temp1 = await getColumn('stations')
	console.log('temp1222',temp1);
	let bool1 = getInclude(temp1.map(it => it.name), ['pmId','pmName','branchLineName'])
	console.log('bool1bool1bool1',bool1);
	if(!bool1) {
		await addColumn('stations','pmId')
		await addColumn('stations','pmName')
		await addColumn('stations','branchLineName')
	}
	let columnArr1 = await getColumn('stations')
	console.log(columnArr1, '30行');
	
	//病害表
	let temp2 = await getColumn('diseases')
	let bool2 = getInclude(temp2.map(it => it.name), ['pmId','pmName','projectName','branchLineName'])
	if(!bool2) {
		await addColumn('diseases','pmId')
		await addColumn('diseases','pmName')
		await addColumn('diseases','projectName')
		await addColumn('diseases','branchLineName')
	}
	let columnArr2 = await getColumn('diseases')
	console.log(columnArr2, '42行');
	
	//上次填报记录
	let temp3 = await getColumn('lastFillingRecord')
	let bool3 = getInclude(temp3.map(it => it.name), ['pmId','pmName'])
	if(!bool3) {
		await addColumn('lastFillingRecord','pmId')
		await addColumn('lastFillingRecord','pmName')
	}
	let columnArr3 = await getColumn('lastFillingRecord')
	console.log(columnArr3, '53行');

	//变更日志表
	let temp4 = await getColumn('diseaseOrderLog')
	let bool4 = getInclude(temp4.map(it => it.name), ['pmId','pmName', 'projectName','branchLineName'])
	if(!bool4) {
		await addColumn('diseaseOrderLog','pmId')
		await addColumn('diseaseOrderLog','pmName')
		await addColumn('diseaseOrderLog','projectName')
		await addColumn('diseaseOrderLog','branchLineName')
	}
	let columnArr4 = await getColumn('diseaseOrderLog')
	console.log(columnArr4, '62行');
	await DB.initDatabase()
	// await DB.clearTable(`diseases`)
	// await DB.clearTable(`stations`)
	// await DB.clearTable(`lastFillingRecord`)
	// await DB.clearTable(`diseaseOrderLog`)
	await DB.clearTable(`diseaseGrade`)
	await DB.clearTable(`diseaseContent`)
	await DB.clearTable(`keywordsTable`)
	await DB.clearTable(`diseaseStatus`)
	await DB.clearTable(`repairTable`)
	await DB.clearTable(`stations`)
	//先获取病害等级，再通过病害等级的id获取对应的病害内容编号
	let gradeList =  await doCache(XUNJIAN.diseaseGradeList, {currPage,pageSize,params:{projectId},})
	const taskCacheDiseaseContents = gradeList.map(it=>
		doCache(XUNJIAN.getDiseaseContent, {
			diseaseGradeId:it.id
		})
	)
	await Promise.all(taskCacheDiseaseContents)
	await doCache(XUNJIAN.diseaseKeywordsList, {currPage,pageSize,params:{projectId,keyword:""}})
	await doCache(XUNJIAN.diseaseStatusList, {currPage,pageSize,params:{projectId,keyword:""}})
	await doCache(XUNJIAN.diseaseMaterialList, {currPage,pageSize,params:{projectId,queryStr:""}})
	//缓存区间/站点树形数据
	await doCache(XUNJIAN.getPlanLineSectionSiteStateTreeByLike,{projectId,type:'inspect',projectStates:["zj","zt"]})
}
export function  getInclude(arr1, arr2) {
  // 遍历第二个数组中的每个元素
  for (let i = 0; i < arr2.length; i++) {
    // 如果当前元素不在第一个数组中，则返回 false
    if (!arr1.includes(arr2[i])) {
      return false;
    }
  }
  // 所有元素均位于第一个数组中，返回 true
  return true;
}
//查询表格所有列
export async function getColumn(tableName) {
	 return  await DB.select(`PRAGMA  table_info(${tableName})`)	 
}
//添加新列（如果不存在）
export async function addColumn(tableName,columnName) {
	 let allColumn = await getColumn(tableName)
	 let isExists = getInclude(allColumn.map(it => it.name), [columnName])
	 if(isExists) {
		 console.log(tableName + '存在' + columnName + '所以不添加');
	 }else {
		 console.log('不存在列则新增一列',columnName);
		 return  await DB.execute(`alter table ${tableName} add column ${columnName} varchar `) 
	 }
	 
} 